package demo.ftp;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FTPDemo {

    private static Logger logger = LoggerFactory.getLogger(FTPDemo.class);

    public static String host = "172.16.0.142";
    public static String user = "test_download";
    public static String pass = "test_download";
    public static int port = 21;

    @Test
    public void demo1() {
        String localFilePath = "C:\\Users\\hanjy\\Desktop\\风控系统2.0.docx";
        FTPClient ftpClient = null;
        try {
            ftpClient = FtpUtils.connectAndLogin(host, port, user, pass);
            logger.info("pwd:{}", ftpClient.printWorkingDirectory());
            logger.info("ftpClient.changeWorkingDirectory(\"/risk/ma\") = {}",
                    ftpClient.changeWorkingDirectory("/risk/ma"));
            logger.info("pwd:{}", ftpClient.printWorkingDirectory());
            logger.info("ftpClient.makeDirectory(\"/risk/ma\") = {}", ftpClient.makeDirectory("/risk/ma"));
            logger.info("pwd:{}", ftpClient.printWorkingDirectory());

            FileInputStream fis = new FileInputStream(localFilePath);

            boolean ok = ftpClient.storeFile("/risk/ma/风控系统2.0.docx", fis);
            logger.info("{}", ok);

            ByteArrayOutputStream out = new ByteArrayOutputStream();
            ftpClient.retrieveFile("/risk/ma/风控系统2.0.docx", out);

            FileOutputStream fos = new FileOutputStream("C:\\Users\\hanjy\\Downloads\\风控系统2.0.docx");
            fos.write(out.toByteArray());
            fos.close();
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    logger.error("disconnect FTP server failed", e);
                }
            }
        }
    }

    
    
    @Test
    public void makeDirectory() {
        FTPClient ftpClient = null;
        String ftpPath = "risk/ma/tmp/a//12/d/";
        try {
            ftpClient = FtpUtils.connectAndLogin(host, port, user, pass);
            logger.info("pwd:{}", ftpClient.printWorkingDirectory());
            boolean ok = FtpUtils.makeDirectory(ftpClient, ftpPath);
            logger.info("createDirecroty {} return {}", ftpPath, ok);
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    logger.error("disconnect FTP server failed", e);
                }
            }
        }
    }

    @Test
    public void changeWorkingDirectory() {
        FTPClient ftpClient = null;
        String ftpPath = "/risk/ma/tmp";
        try {
            ftpClient = FtpUtils.connectAndLogin(host, port, user, pass);
            logger.info("pwd:{}", ftpClient.printWorkingDirectory());
            boolean ok = ftpClient.changeWorkingDirectory(ftpPath);
            logger.info("ftpClient.changeWorkingDirectory({}) = {}", ftpPath, ok);
            if (!ok) {
                ok = ftpClient.makeDirectory(ftpPath);
                logger.info("ftpClient.makeDirectory({}) = {}", ftpPath, ok);
            }
            if (ok) {
                ok = ftpClient.changeWorkingDirectory(ftpPath);
                logger.info("ftpClient.changeWorkingDirectory({}) = {}", ftpPath, ok);
                logger.info("pwd:{}", ftpClient.printWorkingDirectory());
            }
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    logger.error("disconnect FTP server failed", e);
                }
            }
        }
    }

    @Test
    public void list() {
        FTPClient ftpClient = null;
        String ftpPath = "/risk/ma/tmp/tmp";
        try {
            ftpClient = FtpUtils.connectAndLogin(host, port, user, pass);
            logger.info("pwd:{}", ftpClient.printWorkingDirectory());
            FtpUtils.printFTPFile(ftpClient.listFiles());
            FtpUtils.printFTPFile(ftpClient.listDirectories());
            FTPFile[] ftpFileArray = ftpClient.listFiles(ftpPath);
            FtpUtils.printFTPFile(ftpClient.listFiles(ftpPath));
            FtpUtils.printFTPFile(ftpClient.listDirectories(ftpPath));
        } catch (Exception e) {
            logger.error("", e);
        } finally {
            if (ftpClient != null && ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    logger.error("disconnect FTP server failed", e);
                }
            }
        }
    }

    static void demo() {
        FTPClient ftpClient = new FTPClient();
        FTPClientConfig config = new FTPClientConfig();
        // config.setXXX(YYY); // change required options
        ftpClient.setControlKeepAliveTimeout(300); // set timeout to 5 minutes
        // for example config.setServerTimeZoneId("Pacific/Pitcairn")
        ftpClient.configure(config);
        boolean error = false;
        try {
            String server = "ftp.example.com";
            ftpClient.connect(server);
            System.out.println("Connected to " + server + ".");
            System.out.print(ftpClient.getReplyString());

            // After connection attempt, you should check the reply code to verify success.
            int reply = ftpClient.getReplyCode();
            String[] replyStrings = ftpClient.getReplyStrings();
            if (replyStrings != null && replyStrings.length > 0) {
                System.out.println(Arrays.toString(replyStrings));
            }

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftpClient.disconnect();
                System.err.println("FTP server refused connection.");
                System.exit(1);
            }

            ftpClient.sendNoOp();
            // transfer files
            ftpClient.logout();
        } catch (IOException e) {
            error = true;
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                    // do nothing
                }
            }
            System.exit(error ? 1 : 0);
        }

    }

}
